package com.example.icedcap.topeka_fake.widget.quiz;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.icedcap.topeka_fake.R;
import com.example.icedcap.topeka_fake.model.Category;
import com.example.icedcap.topeka_fake.model.quiz.FillBlankQuiz;

/**
 * Author: doushuqi
 * Date: 15/7/18
 * Time: 下午3:20
 * Email: shuqi.dou@singuloid.com
 */
public class FillBlankQuizView extends TextInputQuizView<FillBlankQuiz> {
    private static final String KEY_ANSWER = "ANSWER";
    private EditText mEditText;

    public FillBlankQuizView(Context context, Category category, FillBlankQuiz quiz) {
        super(context, category, quiz);
    }

    @Override
    protected View createQuizContentView() {
        String start = getQuiz().getStart();
        String end = getQuiz().getEnd();
        if (null != start || null != end) {
            return getStartEndView(start, end);
        }
        if (null == mEditText) {
            mEditText = createEditText();
        }

        return mEditText;
    }

    @Override
    protected boolean isAnswerCorrect() {
        return getQuiz().isAnswerCorrect(mEditText.getText().toString());
    }

    @Override
    public Bundle getUserInput() {
        Bundle bundle = new Bundle();
        bundle.putString(KEY_ANSWER, mEditText.getText().toString());
        return bundle;
    }

    @Override
    public void setUserInput(Bundle savedInput) {
        if (null == savedInput) {
            return;
        }
        mEditText.setText(savedInput.getString(KEY_ANSWER));
    }

    private View getStartEndView(String start, String end) {
        LinearLayout container = (LinearLayout) getLayoutInflater().inflate(R.layout.quiz_fill_blank_with_surroundings, this, false);
        mEditText = (EditText) container.findViewById(R.id.quiz_edit_text);
        mEditText.addTextChangedListener(this);
        mEditText.setOnEditorActionListener(this);
        TextView startView = (TextView) container.findViewById(R.id.start);
        setExitingContentOrHide(startView, start);
        TextView endView = (TextView) container.findViewById(R.id.end);
        setExitingContentOrHide(endView, end);
        return container;
    }

    private void setExitingContentOrHide(TextView view, String content) {
        if (null == content) {
            view.setVisibility(GONE);
        } else {
            view.setVisibility(VISIBLE);
            view.setText(content);
        }
    }
}
